package com.example.scaletest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.mylibrary.scaleweihgt.LogUtil;
import com.example.mylibrary.scaleweihgt.ScaleSerialWeight;
import com.example.mylibrary.scaleweihgt.UpdateWeight;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.NumberUtil;


public class MainAct extends Activity implements UpdateWeight {
    private ScaleSerialWeight serialWeight = null;
    private TextView tv_unit;
    private TextView tv_weight;
    private RecyclerView ry_set;
    private Button btn_sta;
    private LinearLayout rl_head_w;
    private Button btn_zero;
    private Button btn_tare;
    private TextView tv_tare;
    private RecyclerView ry_out;
    private TextView tv_version;
    private TextView tv_ts_left;
    private TextView tv_camera;
    private TextView tv_printer;

    private List<ItemSetEntity> setEntities;
    private ScaleWindow window;

    List<ItemSetEntity> divis;
    List<ItemSetEntity> decimals;
    List<ItemSetEntity> zeros;
    List<ItemSetEntity> autoZeros;
    List<ItemSetEntity> aZerot;
    List<ItemSetEntity> filts;
    List<ItemSetEntity> units;
    List<ItemSetEntity> samps;

    final String[] arrDECI = ScaleSerialWeight.lsDECI;//小数点
    final String[] arrZero = ScaleSerialWeight.lsHZero;//手动归零范围
    final String[] arrAZero = ScaleSerialWeight.lsZero;//自动零点追踪
    final String[] arrADZero = ScaleSerialWeight.lsAZero;//上电自动归零范围
    final String[] arrfilt = ScaleSerialWeight.lsFilt;//滤波深度调整
    final String[] unitss = ScaleSerialWeight.lsunits;//单位
    final String[] siviss = ScaleSerialWeight.lsdivis;//感量
    final String[] samp = ScaleSerialWeight.samps;//采样频率

    private Context context;
    private float weight;

    private static final String RED = "red_light";
    private static final String GREEN = "green_light";
    private static final String YELLOW = "yellow_light";
    private static final String WARN = "warning_light";
    private List<IoEntity> outEntities;
    private List<IoEntity> inEntities;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.man_act);
        context = this;
        initView();
        initScale();


    }

    private void initView() {
        tv_tare = findViewById(R.id.tv_tare);
        tv_weight = findViewById(R.id.tv_weight);
        tv_unit = findViewById(R.id.tv_unit);
        ry_set = findViewById(R.id.ry_set);
        btn_sta = findViewById(R.id.btn_sta);
        rl_head_w = findViewById(R.id.rl_head_w);


        btn_zero = findViewById(R.id.btn_zero);
        btn_tare = findViewById(R.id.btn_tare);
        ry_out = findViewById(R.id.ry_out);
        tv_version = findViewById(R.id.tv_version);
        tv_ts_left = findViewById(R.id.tv_ts_left);
        tv_camera = findViewById(R.id.tv_camera);
        tv_printer = findViewById(R.id.tv_printer);

        tv_printer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainAct.this,FunctionActivity.class));
            }
        });



        outEntities = new ArrayList<>();
        inEntities = new ArrayList<>();
        for (int i = 1; i < 17; i++) {
            IoEntity entity = new IoEntity();
            entity.setPosition(i);
            entity.setId((long) i);
            if (i < 9) {
                entity.setFlag(1);
                switch (i) {
                    case 1:
                        entity.setName(RED);
                        break;
                    case 2:
                        entity.setName(GREEN);
                        break;
                    case 3:
                        entity.setName(YELLOW);
                        break;
                    case 4:
                        entity.setName(WARN);
                        break;
                    default:
                        entity.setName(i + "");
                }
                outEntities.add(entity);
            } else {
                entity.setFlag(2);
                entity.setName(i + "");
                inEntities.add(entity);
            }
        }

        LogUtil.e("输出io= " + outEntities.size());
        LogUtil.e("输入io= " + inEntities.size());

        MyGridLayoutManager gridLayoutManager = new MyGridLayoutManager(this, outEntities.size());
        ry_out.setLayoutManager(gridLayoutManager);
        OutAdapter outAdapter = new OutAdapter(R.layout.item_out, outEntities);
        ry_out.setAdapter(outAdapter);
        outAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int i) {
//                switch (view.getId()){
//                    case R.id.tv_io_switch:
                serialWeight.setOutIo(outEntities.get(i).getPosition(), outEntities.get(i).getVoltage() == 0 ? 1 : 0);

                outEntities.get(i).setVoltage(outEntities.get(i).getVoltage() == 0 ? 1 : 0);
                outAdapter.notifyItemChanged(i);
//                        break;
//                }
            }
        });


        tv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainAct.this,CameraAct.class));
            }
        });

        btn_zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                serialWeight.setWeightZero();
            }
        });

        btn_tare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                serialWeight.setWeightTare(0);//传0是连续去皮
//                serialWeight.setWeightTare(weight);
            }
        });

        btn_sta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window = new ScaleWindow(context);
                window.show(rl_head_w);
//                window.setInternalCount(mScale.getInternalCount());
                window.SetOnScaleClickListener(new ScaleWindow.OnScaleClickListener() {
                    @Override
                    public void onClickOne() {
                        serialWeight.setWeightAdz();
                        LogUtil.e("校正0点");
                    }

                    @Override
                    public void onClickTwo(float f) {
                        serialWeight.setWeightLoad(f);
                        LogUtil.e("校正重量" + f);
                    }
                });
            }
        });
    }

    private void initScale() {
        serialWeight = ScaleSerialWeight.getInstance("/dev/ttyS3");
        serialWeight.scaleStart();
        serialWeight.setUpdateWeight(this);
    }


    @Override
    public void updateWeight(boolean b, String s, String s1) {//称参数回调b:是否稳定s:内码 s1：重量
//        LogUtil.e(b + s + s1);
        weight = NumberUtil.parseFloat(s1);
        SpUtil.put(Config.INNER_CODE, s);
        tv_weight.setText(s1);

    }

    @Override
    public void zeroClear() {//清零回调
        Toast.makeText(context, "清零成功", Toast.LENGTH_SHORT).show();
        tv_tare.setText("T=" + serialWeight.getWeightStr(0));
    }

    @Override
    public void tareClear(float v) {//去皮回调
        Toast.makeText(context, "去皮成功" + v, Toast.LENGTH_SHORT).show();
        tv_tare.setText("T=" + serialWeight.getWeightStr(v));
    }

    @Override
    public void scaleBaseDataOver() {//获取称积分参数完成回调

        setScaleData();

        LogUtil.e(serialWeight.getWeightStr(weight) + serialWeight.getUnitStr());
        tv_unit.setText(serialWeight.getUnitStr());
        tv_tare.setText("T=" + serialWeight.getWeightStr(0));
        tv_version.setText("版本号:  v"+serialWeight.getSdkVersion());

       float scaleD = (float) NumberUtil.mul(Float.parseFloat(arrDECI[serialWeight.getDECI_t()] + (arrDECI[serialWeight.getDECI_t()].contains(".") ? "1" : ".1")), Float.parseFloat(siviss[serialWeight.getDIVI_t()]) * 10);
        LogUtil.e("D=" + scaleD + "  deci=" + Float.parseFloat(arrDECI[serialWeight.getDECI_t()] + "1"));
        float scaleMin = arrDECI[serialWeight.getDECI_t()].contains(".") ? NumberUtil.round(NumberUtil.mul(scaleD * 1000 / serialWeight.getKg(), 20), serialWeight.getDECI_t()).floatValue() : NumberUtil.round(NumberUtil.mul(scaleD, 20), serialWeight.getDECI_t()).floatValue();
        tv_ts_left.setText("   MAX:" + serialWeight.getMAX_t() + serialWeight.getUnitStr() + " Min:" + NumberUtil.toStr(scaleMin) + serialWeight.getUnitStr() + " d=" + scaleD + serialWeight.getUnitStr());


    }

    int rposition;

    private void setScaleData() {
        divis = new ArrayList<>();
        zeros = new ArrayList<>();
        decimals = new ArrayList<>();
        autoZeros = new ArrayList<>();
        aZerot = new ArrayList<>();
        filts = new ArrayList<>();
        units = new ArrayList<>();
        samps = new ArrayList<>();


        for (int i = 0; i < samp.length; i++) {
            if (serialWeight.getSAMP_t() == i) {
                samps.add(new ItemSetEntity(serialWeight.getSAMP_t(), true, samp[serialWeight.getSAMP_t()]));
            } else {
                samps.add(new ItemSetEntity(i, false, samp[i]));
            }
        }

        for (int i = 0; i < siviss.length; i++) {
            if (serialWeight.getDIVI_t() == i) {
                divis.add(new ItemSetEntity(serialWeight.getDIVI_t(), true, siviss[serialWeight.getDIVI_t()]));
            } else {
                divis.add(new ItemSetEntity(i, false, siviss[i]));
            }
        }
        for (int i = 0; i < unitss.length; i++) {
            if (serialWeight.getUnit() == i) {
                units.add(new ItemSetEntity(serialWeight.getUnit(), true, unitss[serialWeight.getUnit()]));
            } else {
                units.add(new ItemSetEntity(i, false, unitss[i]));
            }
        }

        for (int i = 0; i < arrZero.length; i++) {
            if (i == serialWeight.getHZERO_t()) {
                zeros.add(new ItemSetEntity(serialWeight.getHZERO_t(), true, arrZero[serialWeight.getHZERO_t()]));
            } else {
                zeros.add(new ItemSetEntity(i, false, arrZero[i]));
            }
        }
        for (int i = 0; i < arrDECI.length; i++) {
            if (i == serialWeight.getDECI_t()) {
                decimals.add(new ItemSetEntity(serialWeight.getDECI_t(), true, arrDECI[serialWeight.getDECI_t()]));
            } else {
                decimals.add(new ItemSetEntity(i, false, arrDECI[i]));
            }
        }
        for (int i = 0; i < arrADZero.length; i++) {
            if (i == serialWeight.getAZEROR_t()) {
                autoZeros.add(new ItemSetEntity(serialWeight.getAZEROR_t(), true, arrADZero[serialWeight.getAZEROR_t()]));
            } else {
                autoZeros.add(new ItemSetEntity(i, false, arrADZero[i]));
            }
        }
        for (int i = 0; i < arrAZero.length; i++) {
            if (i == serialWeight.getAZEROT_t()) {
                aZerot.add(new ItemSetEntity(serialWeight.getAZEROT_t(), true, arrAZero[serialWeight.getAZEROT_t()]));
            } else {
                aZerot.add(new ItemSetEntity(i, false, arrAZero[i]));
            }
        }
        for (int i = 0; i < arrfilt.length; i++) {
            if (i == serialWeight.getFILT_t()) {
                filts.add(new ItemSetEntity(serialWeight.getFILT_t(), true, arrfilt[serialWeight.getFILT_t()]));
            } else {
                filts.add(new ItemSetEntity(i, false, arrfilt[i]));
            }
        }

        setEntities = new ArrayList<>();
        setEntities.add(new ItemSetEntity(1, false, getString(R.string.point_set), arrDECI[serialWeight.getDECI_t()]));
        setEntities.add(new ItemSetEntity(2, false, getString(R.string.zero_the_range), arrZero[serialWeight.getHZERO_t()]));
        setEntities.add(new ItemSetEntity(3, false, getString(R.string.zero_tracking), arrAZero[serialWeight.getAZEROT_t()]));
        setEntities.add(new ItemSetEntity(4, false, getString(R.string.zero_range_on_power_on), arrADZero[serialWeight.getAZEROR_t()]));
        setEntities.add(new ItemSetEntity(5, false, getString(R.string.filter_depth_adjustment), arrfilt[serialWeight.getFILT_t()]));
        setEntities.add(new ItemSetEntity(6, false, getString(R.string.range), serialWeight.getMAX_t() + unitss[serialWeight.getUnit()]));
        setEntities.add(new ItemSetEntity(7, false, getString(R.string.unit), unitss[serialWeight.getUnit()]));
        setEntities.add(new ItemSetEntity(8, false, getString(R.string.sensitive_quality), siviss[serialWeight.getDIVI_t()]));
        setEntities.add(new ItemSetEntity(9, false, getString(R.string.sample_frequency), samp[serialWeight.getSAMP_t()]));
        LinearLayoutManager manager = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
        ry_set.setLayoutManager(manager);
        SetAdapter adapter = new SetAdapter(R.layout.item_set, setEntities);
        ry_set.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                setEntities.get(position).setChose(true);
                setEntities.get(rposition).setChose(false);
                adapter.notifyDataSetChanged();
                rposition = position;
                switch (position) {
                    case 0://小数点设置
                        SingleChoicePopUpWindow popUpWindowd = new SingleChoicePopUpWindow(context, decimals);
                        popUpWindowd.show(view);
                        popUpWindowd.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {

                                serialWeight.setWeightDeic(option.getId());
                                for (int g = 0; g < decimals.size(); g++) {
                                    if (decimals.get(g).getName().equals(option.getName())) {
                                        decimals.get(g).setChose(true);
                                    } else {
                                        decimals.get(g).setChose(false);
                                    }
                                }
                                LogUtil.e("小数点==" + option.getId());
//                                    AndroidUtil.toast("设置成功");
//                                    SpUtil.put(Config.DECIMAL_FLAG,option.getId());
                                setEntities.get(position).setSubName(decimals.get(option.getId()).getName());
                                popUpWindowd.dismiss();
                                adapter.notifyDataSetChanged();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 1://手动归零范围
                        SingleChoicePopUpWindow popUpWindowz = new SingleChoicePopUpWindow(context, zeros);
                        popUpWindowz.show(view);
                        popUpWindowz.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightHzero(option.getId());
                                for (int k = 0; k < zeros.size(); k++) {
                                    if (zeros.get(k).getName().equals(option.getName())) {
                                        zeros.get(k).setChose(true);
                                    } else {
                                        zeros.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(zeros.get(option.getId()).getName());
                                popUpWindowz.dismiss();
                                adapter.notifyDataSetChanged();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 2://自动零点追踪
                        SingleChoicePopUpWindow popUpWindowa = new SingleChoicePopUpWindow(context, aZerot);
                        popUpWindowa.show(view);
                        popUpWindowa.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightAzerot(option.getId());
                                for (int k = 0; k < aZerot.size(); k++) {
                                    if (aZerot.get(k).getName().equals(option.getName())) {
                                        aZerot.get(k).setChose(true);
                                    } else {
                                        aZerot.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(aZerot.get(option.getId()).getName());
//                                    AndroidUtil.toast("设置成功");
                                adapter.notifyDataSetChanged();
                                popUpWindowa.dismiss();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 3://上电自动归零范围
                        SingleChoicePopUpWindow popUpWindowb = new SingleChoicePopUpWindow(context, autoZeros);
                        popUpWindowb.show(view);
                        popUpWindowb.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightAzeror(option.getId());
                                for (int k = 0; k < autoZeros.size(); k++) {
                                    if (autoZeros.get(k).getName().equals(option.getName())) {
                                        autoZeros.get(k).setChose(true);
                                    } else {
                                        autoZeros.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(autoZeros.get(option.getId()).getName());
//                                    AndroidUtil.toast("设置成功");
                                adapter.notifyDataSetChanged();
                                popUpWindowb.dismiss();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 4://滤波深度调整
                        SingleChoicePopUpWindow popUpWindowc = new SingleChoicePopUpWindow(context, filts);
                        popUpWindowc.show(view);
                        popUpWindowc.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightFilt(option.getId());
                                for (int k = 0; k < filts.size(); k++) {
                                    if (filts.get(k).getName().equals(option.getName())) {
                                        filts.get(k).setChose(true);
                                    } else {
                                        filts.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(filts.get(option.getId()).getName());
//                                    AndroidUtil.toast("设置成功");
                                adapter.notifyDataSetChanged();
                                popUpWindowc.dismiss();
//                                    mScale.setMaxRange(5);

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 5://最大值
                        SingleChoicePopUpWindow popUpWindowm = new SingleChoicePopUpWindow(context, null);
                        popUpWindowm.show(view);
                        popUpWindowm.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                                serialWeight.setWeightMax(weight);
                                setEntities.get(position).setSubName(weight + unitss[serialWeight.getUnit()]);
                                adapter.notifyDataSetChanged();
                                popUpWindowm.dismiss();
                            }
                        });
                        break;
                    case 6://选择单位单位
                        SingleChoicePopUpWindow popUpWindowu = new SingleChoicePopUpWindow(context, units);
                        popUpWindowu.show(view);
                        popUpWindowu.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightUnit(option.getId());
                                for (int k = 0; k < units.size(); k++) {
                                    if (units.get(k).getName().equals(option.getName())) {
                                        units.get(k).setChose(true);
                                    } else {
                                        units.get(k).setChose(false);
                                    }

                                }
//                                SpUtil.put(UNIT_FLAG,option.getName());
//                                AndroidUtil.toast("设置成功");
                                setEntities.get(position).setSubName(option.getName());
                                adapter.notifyDataSetChanged();
                                popUpWindowu.dismiss();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 7://自动零点追踪
                        SingleChoicePopUpWindow popUpWindowk = new SingleChoicePopUpWindow(context, divis);
                        popUpWindowk.show(view);
                        popUpWindowk.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightDivi(option.getId());
                                for (int k = 0; k < divis.size(); k++) {
                                    if (divis.get(k).getName().equals(option.getName())) {
                                        divis.get(k).setChose(true);
                                    } else {
                                        divis.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(divis.get(option.getId()).getName());
//                                    AndroidUtil.toast("设置成功");
                                adapter.notifyDataSetChanged();
                                popUpWindowk.dismiss();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });
                        break;
                    case 8:
                        SingleChoicePopUpWindow popUpWindowui = new SingleChoicePopUpWindow(context, samps);
                        popUpWindowui.show(view);
                        popUpWindowui.setOnOptionSelectedListener(new SingleChoicePopUpWindow.OnOptionSelectedListener() {
                            @Override
                            public void onOptionSelected(ItemSetEntity option) {
                                serialWeight.setWeightSi(option.getId());
                                for (int k = 0; k < samps.size(); k++) {
                                    if (samps.get(k).getName().equals(option.getName())) {
                                        samps.get(k).setChose(true);
                                    } else {
                                        samps.get(k).setChose(false);
                                    }

                                }
                                setEntities.get(position).setSubName(samps.get(option.getId()).getName());
//                                    AndroidUtil.toast("设置成功");
                                adapter.notifyDataSetChanged();
                                popUpWindowui.dismiss();

                            }

                            @Override
                            public void onSaveWeight(int weight) {

                            }
                        });

                        break;
                }
            }
        });

    }

    @Override
    public void setOk(boolean ok) {//设置回调
        LogUtil.e("设置成功" + ok);
        Toast.makeText(context, "设置成功", Toast.LENGTH_SHORT).show();


    }

    @Override
    public void setIoInit(int i, int i1) {//IO输出i:位置  i1:电平高低

    }
}
